<template>
  <TreeTableLayout>
    <template #tree>
      <Tree @query="doQuery" :gatewayType="0"></Tree>
    </template>
    <template #table>
      <RightTableLayout :slotName="['search', 'table', 'pagination']">
        <template #search>
          <Query :columns="columns" @query="doQuery"></Query>
        </template>
        <template #table>
          <el-table :empty-text="i18n.fy.nodata" :data="data.tableData" height="100%" border v-loading="data.loading" :element-loading-text="i18n.fy.loading">
            <el-table-column prop="id" label="ID" width="70" />
            <el-table-column prop="nickName" :label="i18n.fy.设备昵称" width="150" />
            <el-table-column prop="type" :label="i18n.fy.yptxx_type" width="90">
              <template #default="scope">
                {{ showType(scope.row.type) }}
              </template>
            </el-table-column>
            <el-table-column prop="accessKey" :label="i18n.fy.设备Key" :show-overflow-tooltip="true" />
            <el-table-column prop="accessSecret" width="150" :label="i18n.fy.设备Secret" :show-overflow-tooltip="true" />
            <el-table-column prop="consumerGroupId" :label="i18n.fy.消费组" :show-overflow-tooltip="true" />
            <el-table-column prop="iotinstanceId" :label="i18n.fy.实例ID" :show-overflow-tooltip="true" />
            <el-table-column prop="clientId" :label="i18n.fy.设备ID" width="80" />
            <el-table-column prop="host" :label="i18n.fy.接入域名" width="150" :show-overflow-tooltip="true" />
            <el-table-column prop="regionId" :label="i18n.fy.域名地区" width="150" />
            <el-table-column prop="productName" :label="i18n.fy.产品名称" width="150" />
            <el-table-column prop="productKey" :label="i18n.fy.产品公钥" width="150" />
            <el-table-column prop="deviceName" :label="i18n.fy.设备名称" width="150" />
            <el-table-column prop="gatewayGroup" :label="i18n.fy.网关组" width="100"></el-table-column>
            <el-table-column prop="gatewayType" :label="i18n.fy.网关类型" width="100">
              <template #default="scope">
                <span>{{ scope.row.gatewayType == 1 ? i18n.fy.无线 : i18n.fy.有线 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="available" :label="i18n.fy.有效性" width="80">
              <template #default="scope">
                <span :class="'available' + scope.row.available">
                  {{ scope.row.available == 1 ? "有效" : "无效" }}
                </span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" :label="i18n.fy.操作" width="220">
              <template #default="scope">
                <span v-if="scope.row.type == 1 || scope.row.type == -1"> </span>
                <div v-else>
                  <span class="device">
                    <el-button type="warning" size="small" @click="getProductAndDevice(scope.row)">
                      {{ i18n.language == "zh-cn" ? "获取产品信息" : "Obtainproductinformation" }}
                    </el-button>
                    <el-button type="primary" style="background: #1e9fff" size="small" @click="edit(scope.row)">
                      {{ i18n.language == "zh-cn" ? "编辑" : "edit" }}
                    </el-button>
                  </span>
                  <span class="device">
                    <el-button type="warning" size="small" @click="getDeviceInfoNode(scope.row)">
                      {{ i18n.language == "zh-cn" ? "获取设备拓扑" : "Obtaindevicetopology" }}
                    </el-button>
                    <el-button type="danger" size="small" @click="deviceReboot(scope.row)">
                      {{ i18n.language == "zh-cn" ? "重启" : "Restart" }}
                    </el-button>
                  </span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template #pagination>
          <el-pagination @size-change="onChanSize" @current-change="onChanPage" v-model:current-page="data.queryForm.page" v-model:page-size="data.queryForm.limit" :total="data.total" />
        </template>
      </RightTableLayout>
    </template>
  </TreeTableLayout>
  <div style="display: none; padding: 20px; text-align: center" class="bgimg" id="saveOrUpdateDiv">
    <form class="layui-form" lay-filter="dataFrm" id="dataFrm">
      <input type="hidden" name="fid" value="1" />
      <input type="hidden" name="type" value="0" />
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">设备昵称:</label>
          <div class="layui-input-inline">
            <input type="hidden" name="id" />
            <input type="text" name="nickName" lay-verify="required" placeholder="请输入设备名称" autocomplete="off" class="layui-input" />
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">设备Key:</label>
          <div class="layui-input-inline">
            <input type="text" name="accessKey" lay-verify="required" placeholder="请输入设备Key" autocomplete="off" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">设备Secret:</label>
          <div class="layui-input-inline">
            <input type="text" name="accessSecret" autocomplete="off" class="layui-input" />
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">消费组:</label>
          <div class="layui-input-inline">
            <input type="text" name="consumerGroupId" autocomplete="off" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">实例ID:</label>
          <div class="layui-input-inline">
            <input type="text" name="iotinstanceId" autocomplete="off" class="layui-input" />
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">设备ID:</label>
          <div class="layui-input-inline">
            <input type="text" name="clientId" autocomplete="off" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">接入域名:</label>
          <div class="layui-input-inline">
            <input type="text" name="host" autocomplete="off" class="layui-input" />
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">域名地区:</label>
          <div class="layui-input-inline">
            <input type="text" name="regionId" autocomplete="off" class="layui-input" />
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">网关组:</label>
          <div class="layui-input-inline">
            <input type="text" name="gatewayGroup" autocomplete="off" class="layui-input" />
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">网关类型:</label>
          <div class="layui-input-inline">
            <input type="radio" name="gatewayType" value="1" title="无线" checked="checked" />
            <input type="radio" name="gatewayType" value="0" title="有线" />
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">有效性:</label>
          <div class="layui-input-inline">
            <input type="radio" name="state" value="1" title="有效" checked="checked" />
            <input type="radio" name="state" value="0" title="无效" />
          </div>
        </div>
      </div>
      <div class="layui-form-item" style="text-align: center">
        <div class="layui-input-block">
          <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release" lay-filter="doSubmit" lay-submit="">
            {{ i18n.language == "zh-cn" ? "提交" : "submit" }}
          </button>
          <button type="reset" class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh">
            {{ i18n.language == "zh-cn" ? "重置" : "resetting" }}
          </button>
        </div>
      </div>
    </form>
  </div>
</template>

<script setup>
defineOptions({ name: "CloudPlatform" });
import RightTableLayout from "@/views/workbench/components/RightTableLayout.vue";
import TreeTableLayout from "@/views/workbench/components/TreeTableLayout.vue";
import Query from "@/components/query.vue";
import Tree from "@/components/tree.vue";

import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();
import layer from "layui-layer";
import * as xlsx from "xlsx"; // Vue3 版本
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
let $httpUrl = globalProperties.$httpUrl;
let columns = reactive({ nickName: { label: i18n.fy.设备昵称, queryValue: "" } });

let data = reactive({
  queryForm: {
    page: 1,
    limit: 100,
  },
  tableData: [],
  total: 0,
  dialog: false,
  form: {},
  rules: {
    name: [{ required: true, message: "请输入姓名", trigger: "change" }],
    role: [{ required: true, message: "请选择岗位", trigger: "change" }],
  },
});
//表头数据切换
const changeTableHead = (tableData, fieldName) => {
  const list = tableData.map((item) => {
    const obj = {};
    for (const k in item) {
      if (fieldName[k]) {
        obj[fieldName[k]] = item[k];
      }
    }
    return obj;
  });
  return list;
};
// 重置查询表单
const reQueryForm = () => {
  data.queryForm = {
    page: 1,
    limit: 100,
  };
};

const currentChange = (page) => {
  pageData.queryForm.page = page;
  getList();
};

const sizeChange = (size) => {
  data.queryForm.page = size;
  getList();
};
// 新增
const add = () => {};
const formToJson = (data) => {
  data = data.replace(/&/g, '","');
  data = data.replace(/=/g, '":"');
  data = '{"' + data + '"}';
  return data;
};

let mainIndex = "";
let url = $httpUrl + "/device/addDevice";
const edit = (row) => {
  // 编辑
  url = $httpUrl + "/device/updateDevice";
  mainIndex = layer.open({
    type: 1,
    title: "修改设备",
    content: $("#saveOrUpdateDiv"),
    area: ["50%", "60%"],
    maxmin: true,
    success: function (index) {
      layui.use(["form"], () => {
        let form = layui.form;
        form.val("dataFrm", JSON.parse(JSON.stringify(row)));
        form.render();
        //保存
        form.on("submit(doSubmit)", function (obj) {
          //序列化表单数据
          var params = $("#dataFrm").serialize();
          let json_data = JSON.parse(formToJson(params));
          json_data.nickName = decodeURI(json_data.nickName);
          $axios
            .post("/device/updateDevice", json_data)
            .then((res) => {
              if (res.data.message == "成功") {
                obj = "保存成功";
              }
              layer.msg(obj);
              //关闭弹出层
              layer.close(mainIndex);
              getList();
            })
            .catch((err) => {});
        });
      });
    },
  });
};

const showLoad = (msg, tipsTime = 0) => {
  return layer.msg(msg, {
    icon: 16,
    shade: [0.5, "#f5f5f5"],
    time: tipsTime ? tipsTime : 2000,
    scrollbar: false,
    offset: "auto",
  });
};

const closeLoad = (index) => {
  layer.close(index);
};
let loading = "";
let timer = null;
const getDeviceInfoNode = (data) => {
  let pid = data.id;
  layer.confirm("确定更新设备拓扑吗？", function (index) {
    $.get($httpUrl + "/operation/getDeviceInfoNode", { deviceId: pid }, function (res) {
      loading = showLoad("正在获取节点数...");
      if (res.code === 200) {
        loading = showLoad("获取节点成功！");
        let reqNum = 1;
        loading = showLoad("等待设备获取节点第" + reqNum + "次响应...");
        timer = setInterval(function () {
          $.get($httpUrl + "/operation/getResponseInfo", { reqIndex: JSON.parse(res.data).code }, function (res) {
            if (res.code === 200) {
              clearInterval(timer);
              setTimeout(() => {
                loading = showLoad("正在获取网络拓扑...", 20000);
              }, 0);
              $.get(
                $httpUrl + "/operation/getNetworkTopology",
                {
                  deviceId: pid,
                  nodeCount: -res.data,
                },
                function (res) {
                  if (res.code === 200) {
                    layer.msg("网络拓扑获取成功！");
                    reqNum = 1;
                    loading = showLoad("等待设备获取网络拓扑第" + reqNum + "次响应...");
                    timer = setInterval(function () {
                      $.get($httpUrl + "/operation/getResponseInfo", { reqIndex: res.data.code }, function (res) {
                        if (res.code === 200) {
                          clearInterval(timer);
                          layer.msg("设备获取网络拓扑成功！");
                          tableIns.reload();
                        } else {
                          if (reqNum >= 3) {
                            clearInterval(timer);
                            layer.msg("设备获取网络拓扑响应失败！");
                          } else {
                            reqNum++;
                            loading = showLoad("等待设备获取网络拓扑第" + reqNum + "次响应...");
                          }
                        }
                      });
                    }, 2000);
                  } else {
                    layer.msg("请求失败！");
                  }
                }
              );
            } else {
              if (reqNum >= 10) {
                clearInterval(timer);
                layer.msg("设备获取节点响应失败！");
              } else {
                reqNum++;
                loading = showLoad("等待设备获取节点第" + reqNum + "次响应...");
              }
            }
          });
        }, 2000);
      } else {
        layer.msg("请求失败,请确认是否正确选择设备！");
      }
    });
  });
};

const getProductAndDevice = (data) => {
  $.get($httpUrl + "/operation/getProductAndDevice?deviceId=" + data.id, function (res) {
    if (res.code == 200) {
      layer.msg("获取成功！");
      getList();
    } else {
      layer.msg(res.msg);
    }
  });
};

const deviceReboot = (data) => {
  layer.confirm("确定重启设备[" + data.deviceName + "]吗？", function (index) {
    loading = showLoad("设备重启请求中...");
    $.post(
      $httpUrl + "/operation/deviceRestart",
      {
        deviceFid: data.id,
      },
      function (res) {
        if (res.code === 200) {
          loading = showLoad("设备重启请求成功！");
          let reqNum = 1;
          loading = showLoad("等待设备重启第" + reqNum + "次响应...");
          timer = setInterval(function () {
            $.get($httpUrl + "/operation/getResponseInfo", { reqIndex: res.data.code }, function (res) {
              if (res.code === 200) {
                clearInterval(timer);
                layer.msg("设备重启成功！");
              } else if (res.code === 3014) {
                layer.msg(res.msg, { time: 3500 });
                clearInterval(timer);
              } else {
                if (reqNum >= 3) {
                  $.post($httpUrl + "/operation/delDevice", { deviceFid: data.id }, (res, err) => {
                    if (res.code === 200) {
                      layer.msg("缺少网关板！", { time: 3500 });
                    }
                  });
                  clearInterval(timer);
                } else {
                  reqNum++;
                  loading = showLoad("等待设备重启第" + reqNum + "次响应...");
                }
              }
            });
          }, 2000);
        } else {
          layer.msg("设备重启失败!!缺少CCO!");
        }
      }
    );
  });
};
const onChanSize = (e) => {
  //修改分页数
  data.queryForm.page = 1;
  data.queryForm.limit = e;
  getList();
};
// 修改分页
const onChanPage = (e) => {
  data.queryForm.page = e;
  getList();
};
// 删除
const del = (row) => {
  ElMessageBox.confirm("确认删除?", "提示").then(() => {});
};
const print = () => {
  var html = $(".el-table").prop("outerHTML");
  //获取所有要body中的内容，作为备份
  var oldhtml = $("body").prop("outerHTML");

  //将打印的html赋值给body
  $("body").html(html);
  //打印
  window.print();

  //同时把原来的html还原
  $("body").html(oldhtml);
};
let formRef = ref(null);

const submit = () => {
  // 提交新增/编辑表单
  formRef.value.validate((valid) => {
    if (valid) {
    }
  });
};

const getList = (params) => {
  // 获取表格数据
  let nickName = "";
  if (params.nickName) {
    nickName = params.nickName;
  }
  data.loading = true;
  let obj = {
    ...data.queryForm,
    ...params,
    id: pid.value,
  };
  if (obj.deviceFid) {
    obj.id = obj.deviceFid;
    delete obj.deviceFid;
  }
  $axios.get("/device/queryDeviceAllList", obj).then((res) => {
    data.loading = false;
    res.data.data.records = res.data.data.records.filter((item) => {
      return item.nickName.includes(nickName);
    });
    data.tableData = res.data.data.records;
    data.total = res.data.data.total;
  });
};
let pid = ref("");
const doQuery = (params) => {
  if (params.deviceFid) {
    pid.value = params.deviceFid;
  }
  getList({ ...params, id: pid.value });
};
const getHeight = () => {
  return window.innerHeight - 210 + "px";
};
const getWidth = () => {
  return window.innerWidth - 398 + "px";
};
const showType = (type) => {
  if (type == -1) return "系统";
  if (type == 0) return "云平台";
  if (type == 1) return "云产品";
  if (type == 2) return "云设备";
};
const exports = () => {
  let tableData = data.tableData;
  let fieldNameObj = {
    index: "索引",
    deviceTitle: "设备标题",
  };
  let fileName = "Sheet1";
  const list = changeTableHead(tableData, fieldNameObj);
  // 创建工作表
  const datat = xlsx.utils.json_to_sheet(list);
  // 创建工作簿
  const wb = xlsx.utils.book_new();
  // 将工作表放入工作簿中
  xlsx.utils.book_append_sheet(wb, datat, fileName);
  // 生成文件并下载
  xlsx.writeFile(wb, `${fileName}.xlsx`);
};
onBeforeMount(() => {
  getList({});
});
</script>

<style lang="scss" scoped>
.available1 {
  color: orangered;
}

.layui-form-label {
  line-height: normal;
}

.device {
  display: block;
  padding: 2px 0;
}
</style>
